package com.example.myproject.service.serviceImpl;

import com.example.myproject.service.FileStorageService;
import com.example.myproject.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List;

@Service
public class FileStorageServiceImpl implements FileStorageService {

    @Value("${file.upload-dir}")
    private String uploadDir;
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList("doc","docx", "jpg", "jpeg", "png", "bmp", "gif");
    private static final Logger log = LoggerFactory.getLogger(FileStorageServiceImpl.class);
    @Override
    public String storeFile(MultipartFile file) {
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        log.debug("尝试存储文件：{}", fileName);
        if (fileName.contains("..")) {
            log.warn("文件名不合法，包含路径穿越序列：{}", fileName);
            return String.valueOf(Result.fileStorageError("文件名包含不合法的路径序列: " + fileName));
        }
        String fileExtension = StringUtils.getFilenameExtension(fileName);
        if (!ALLOWED_EXTENSIONS.contains(fileExtension)) {
            log.warn("尝试上传不支持的文件类型：{}", fileExtension);
            return String.valueOf(Result.unsupportedFileType());
        }
        Path targetLocation = Paths.get(uploadDir).resolve(fileName);
        try {
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            log.info("文件存储成功，路径：{}", targetLocation.toString());
            return targetLocation.toString();
        } catch (IOException ex) {
            log.error("无法存储文件：{}，错误：{}", fileName, ex.getMessage());
            return String.valueOf(Result.fileStorageError("无法存储文件: " + fileName + "。请重试。"));
        }
    }

    @Override
    public String deleteFile(String fileName) {
        Path filePath = Paths.get(uploadDir).resolve(fileName);
        log.debug("尝试删除文件：{}", fileName);
        try {
            Files.delete(filePath);
            log.info("文件删除成功：{}", fileName);
        } catch (IOException e) {
            log.error("无法删除文件：{}，错误：{}", fileName, e.getMessage());
            return String.valueOf(Result.fileStorageError("无法删除文件: " + fileName));
        }
        return fileName;
    }

    @Override
    public Path loadFileAsPath(String fileName){
        Path filePath = Paths.get(uploadDir).resolve(fileName);
        log.debug("加载文件路径：{}", fileName);
        if (!Files.exists(filePath)) {
            log.warn("文件未找到：{}", fileName);
            return (Path) Result.fileNotFound();
        }
        log.info("文件路径加载成功：{}", filePath);
        return filePath;
    }
}
